﻿//  Copyright (c) 2010 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Web.Profile;
using System.Security.Cryptography;
using System.Text;
using System.Web.Mvc;

namespace DNA.Mvc
{
    public static class UserExtensions
    {
        private static WebSiteContext Context
        {
            get
            {
                return WebSiteContext.Current;// DependencyResolver.Current.GetService<WebSiteContext>();
            }
        }

        /// <summary>
        /// Identity whether the current user is administrator
        /// </summary>
        /// <param name="user">The user object</param>
        /// <returns></returns>
        public static bool IsAdministrator(this IPrincipal user)
        {
            if (user.Identity != null)
            {
                if (user.IsInRole("administrators"))
                    return true;
            }

            return false;
        }

        /// <summary>
        /// Identity whether the current user is host.
        /// </summary>
        /// <param name="user">The user object</param>
        /// <returns></returns>
        public static bool IsHost(this IPrincipal user)
        {
            if (user.Identity != null)
                return user.Identity.Name.Equals("host", StringComparison.OrdinalIgnoreCase);
            return false;
        }

        /// <summary>
        /// Identity whether the current user is current web owner.
        /// </summary>
        /// <param name="user">The user object</param>
        /// <returns></returns>
        public static bool IsWebOwner(this IPrincipal user)
        {
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                if (user!=null && user.Identity != null && Context!=null && Context.Web!=null)
                    return user.Identity.Name.Equals(Context.Web.Owner, StringComparison.OrdinalIgnoreCase);
            }
            return false;
        }

        /// <summary>
        /// Get the permalink of this user.
        /// </summary>
        /// <param name="user"></param>
        /// <returns>A Uri will be return.</returns>
        public static Uri GetPermalinkUrl(this IPrincipal user)
        {
            return GetPermalinkUrlCore(user.Identity.Name);
        }

        public static Uri GetPermalinkUrl(this MembershipUser user)
        {
            return GetPermalinkUrlCore(user.UserName);
        }

        public static UserProfile GetProfile(this MembershipUser user)
        {
            return GetProfile(user.UserName);
        }

        public static string GetDisplayName(this MembershipUser user)
        {
            return GetDisplayNameCore(user.UserName);
        }

        public static string GetAvatar(this MembershipUser user, int size=0)
        {
            if (user == null)
                return "";

            var profile= GetProfile(user.UserName);
            if (profile == null)
                return "";
            
            string avatar =profile.Avatar;

            if (!string.IsNullOrEmpty(avatar))
            {
                if (size>0)
                    return avatar + "?thumb=true&w=" + size.ToString() + "&h=" + size.ToString();
                return avatar;
            }

            string gravatarEmail = profile["Gravatar"] as string;

            if (!string.IsNullOrEmpty(gravatarEmail))
            {
                return "http://www.gravatar.com/avatar/" + MD5Hash(user.Email.ToLower()).ToLower() + (size>0 ? "?s=" + size.ToString() : "");
            }

            return Context.ApplicationPath + "/Content/Images/no-avatar.gif";
        }

        public static string MD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }

        private static UserProfile GetProfile(string name)
        {
            var profile = UserProfile.GetProfile(name);
            // new ProfileBase();
            //profile.Initialize(name, true);
            return UserProfile.GetProfile(name);// profile;
        }

        private static string GetDisplayNameCore(string name)
        {
            return  GetProfile(name).DisplayName;
            //return string.IsNullOrEmpty(dName) ? name : dName;
        }

        private static Uri GetPermalinkUrlCore(string username)
        {
            Uri url = null;
            //string userLink = WebSite.ApplicationPath + "/sites/" + username + "/index.html";
            string userLink = Context.ApplicationPath + "/sites/" + username + "/index.html";
            if (!Context.EnablePersonalWeb)
                userLink = Context.ApplicationPath + "/account/info?username=" + username;

            Uri.TryCreate(userLink, UriKind.Absolute, out url);
            return url;
        }

        //public static void AddUserID(this MembershipUser user, string openId)
        //{
        //    throw new NotImplementedException();
        //    //WebSite.MembershipService.AddOpenID(user.UserName, openId);
        //}

        //public static void RemoveUserID(this MembershipUser user, string openId)
        //{
        //    throw new NotImplementedException();
        //    //WebSite.MembershipService.DeleteOpenID(user.UserName, openId);
        //}

        //public static string[] GetUserIDs(string userName)
        //{
        //    throw new NotImplementedException();
        //    //var _passports = WebSite.MembershipService.GetUserPassports(userName);
        //    //if ((_passports != null) && (_passports.Count() > 0))
        //    //{
        //    //    return _passports.Select(p => p.UserId).ToArray();
        //    //}
        //    //else
        //    //    return new string[0];
        //}
    }
}